package be.android.forap.gui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.dropbox.client2.exception.DropboxException;

import be.android.forap.ForAp;
import be.android.forap.R;
import be.android.forap.crypto.KeyServerUtil;
import be.android.forap.crypto.PGPDigitalSignature;
import be.android.forap.crypto.PGPEncryption;
import be.android.forap.crypto.CryptoUtil;
import be.android.forap.dataprovider.ContactIntegrityElement;
import be.android.forap.dataprovider.ContactManager;
import be.android.forap.dataprovider.ContactQueries;
import be.android.forap.dataprovider.ContactsIntegrityDb;
import be.android.forap.dataprovider.ForapAdapter;
import be.android.forap.dataprovider.RawContact;
import be.android.forap.dataprovider.RowData;
import be.android.forap.network.DropboxUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;


public class EncryptActivity extends BaseActivity {
	

	private static final String TAG = "EncryptActivity";

	private TextView selected;

	private ViewFlipper viewflipper;
	private Animation animFlipInNext;
	private Animation animFlipOutNext;
	private Animation animFlipInPrevious;
	private Animation animFlipOutPrevious;

	private static final int PICK_CONTACT_REQUEST = 0;
	private static final int SELECT_FILE = 1;
	private static final int SELECT_FOLDER_AND_WRITE = 2;

	public static final String SHARE_BODY_TO_ENCRYPT = "SHARE_BODY_TO_ENCRYPT";
	public static final String FILE_OPEN_TO_ENCRYPT = "FILE_OPEN_TO_ENCRYPT";
	public static final String SELECTED_GLOBAL_ID = "SELECTED_GLOBAL_ID";
	
	private ArrayList<String> selectedContactGlobalIds = new ArrayList<String>();
	private String selectedFilePath;
	private CustomAutoComplete contactInput;
	
	private String outputMessage;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.encrypt);
		//for testing purposes
		((TextView)findViewById(R.id.en_inputText)).setText("Hello World!!!");

		

		selected = (TextView)findViewById(R.id.textSelected);
		viewflipper = (ViewFlipper)findViewById(R.id.en_viewFlipper);
		updateSelectedLabel();
		animFlipInNext = AnimationUtils.loadAnimation(this, R.anim.flipinnext);
		animFlipOutNext = AnimationUtils.loadAnimation(this, R.anim.flipoutnext);
		animFlipInPrevious = AnimationUtils.loadAnimation(this, R.anim.flipinprevious);
		animFlipOutPrevious = AnimationUtils.loadAnimation(this, R.anim.flipoutprevious);

		String globalId = getIntent().getStringExtra(SELECTED_GLOBAL_ID);
		if(!TextUtils.isEmpty(globalId)){
			selectedContactGlobalIds.add(globalId);
			RawContact sc = ContactManager.getRawContactInfo(this, globalId);
			((TextView) findViewById(R.id.en_autoCompleteContact)).setText(sc.getBestName()+";");
		}

		String content = getIntent().getStringExtra(SHARE_BODY_TO_ENCRYPT);
		if(!TextUtils.isEmpty(content)){
			((TextView)findViewById(R.id.en_inputText)).setText(content);
		}

		String path = getIntent().getStringExtra(FILE_OPEN_TO_ENCRYPT);
		if(!TextUtils.isEmpty(path)){
			viewflipper.setDisplayedChild(viewflipper.indexOfChild(findViewById(R.id.en_view_browse)));
			updateSelectedLabel();
			selectedFilePath = path;
			((TextView) findViewById(R.id.en_textview_selectedFile)).setText("Selected file: "+ selectedFilePath);
		}

		contactsAdapter = new ForapAdapter(this, this, false, true);
		checkedList = new boolean[contactsAdapter.getCount()];

		initSelectableContacts();
	}

	public void onResume(){
		super.onResume();
		initSelectableContacts();
	}

	private void initSelectableContacts() {
		contactInput = (CustomAutoComplete) findViewById(R.id.en_autoCompleteContact);
		//contactInput = (AutoCompleteTextView) findViewById(R.id.en_autoCompleteContact);
		//ForapAdapter forapdata = new ForapAdapter(this,this,false,true);
		/*String[] forapDiplayNames = forapdata.getDisplayNames();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,forapDiplayNames);
		contactInput.setAdapter(adapter);*/
		
		
		//SimpleAdapter mAdapter = new SimpleAdapter(this, forapdata.getExtraInfo(), R.layout.autocomplete_dropdown ,new String[] { "Name", "Phone" , "Type" }, new int[] { R.id.ccontName, R.id.ccontNo, R.id.ccontType });
		SimpleAdapter mAdapter = new SimpleAdapter(this, ContactManager.getMultipleRawContactInfo(this,ForAp.getInstance().getForApAccount().name),
				R.layout.autocomplete_dropdown ,new String[] { "Name", "Phone" , "Email" },
				new int[] { R.id.ccontName, R.id.ccontNo, R.id.ccontEmail });
		contactInput.setAdapter(mAdapter);
		contactInput.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> av, View v, int index, long arg) {
				Map<String, String> map = (Map<String, String>) av.getItemAtPosition(index);
				Iterator<String> myVeryOwnIterator = map.keySet().iterator();
				while(myVeryOwnIterator.hasNext()) {
					String key=(String)myVeryOwnIterator.next();
					String value=(String)map.get(key);
					contactInput.setFocusable(false);
					contactInput.setFocusableInTouchMode(false);
					if(key.equals("Name")){
						contactInput.replaceText(value);
						String[] names = contactsAdapter.getDisplayNames();
						for(int i = 0;i<names.length;i++){
							if(names[i].equals(value))
								checkedList[i]= true;
						}
					}
					contactInput.setFocusable(true);
					contactInput.setFocusableInTouchMode(true);
				}               
			}

		});
		/*contactInput = (CustomAutoComplete) findViewById(R.id.en_autoCompleteContact);
		ForapAdapter forapdata = new ForapAdapter(this,this,false,true);
		String[] forapDiplayNames = forapdata.getDisplayNames();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,forapDiplayNames);
		contactInput.setAdapter(adapter);*/
		contactsAdapter = new ForapAdapter(this, this, false, true);
		contactsAdapter.addPersonalRow();
		checkedList = new boolean[contactsAdapter.getCount()];
	}

	public void onClick(View v){
		switch (v.getId()) {
		case R.id.en_button_next:
			viewflipper.setInAnimation(animFlipInNext);
			viewflipper.setOutAnimation(animFlipOutNext);
			viewflipper.showNext();
			updateSelectedLabel();
			break;
		case R.id.en_button_previous:
			viewflipper.setInAnimation(animFlipInPrevious);
			viewflipper.setOutAnimation(animFlipOutPrevious);
			viewflipper.showPrevious();
			updateSelectedLabel();
			break;
		case R.id.en_button_to:
			/*try{
			PGPEncryption.test();
			}catch(Exception e){
				Log.i("TESTRESULT",e.getClass()+"error"+e.getMessage());
			}*/
			popupContactSelect();
			contactInput = (CustomAutoComplete) findViewById(R.id.en_autoCompleteContact);
			Log.d("auto", contactInput.getText().toString());
			//TODO slect from phone add to sms box

			//ContactManager.getPublicKeyFromPhoneNumber(this, "0496987518");
			/*SmsReceiver.addSmsToSentBox("testie", "0479987518", getApplicationContext());
			PendingIntent pi = PendingIntent.getActivity(this, 0,new Intent(this, Object.class), 0);                
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage("0479409147", null, "tada", pi, null);
			/*Intent selectContact = new Intent(EncryptActivity.this, SelectContactsActivity.class);
			startActivityForResult(selectContact, PICK_CONTACT_REQUEST);*/
			break;
		case R.id.en_button_browse:
			Intent selectFile = new Intent(EncryptActivity.this, FileExplorerActivity.class);
			selectFile.putExtra(FileExplorerActivity.START_PATH, "/sdcard/forap");
			selectFile.putExtra(FileExplorerActivity.SELECT_ONLY_FILE_READ, true);
			startActivityForResult(selectFile, SELECT_FILE);
			break;
		case R.id.en_button_encrypt:			 
			encrypt();
			break;
		case R.id.en_button_sign:
			sign();
			break;
		case R.id.en_button_encryptAndSign:
			encryptAndSign();
			break;
		default:
			Toast.makeText(getApplicationContext(), "This button isn't implemented", Toast.LENGTH_SHORT).show();
			break;
		}
	}



	//TODO SLECTOR
	/*protected void contactSelector() {
		super.onResume();
		final Builder build = new Builder(this);
		build.setTitle("List selection");
		build.setCancelable(true);
		RowData rd = null;//extractRowDataFromForapCursor();		
		CustomAdapter adapter = new CustomAdapter(this, rd, rd);
		ListView list = new ListView(this);
		list.setAdapter(adapter);
		ArrayList<String> selections = new ArrayList<String>();
		final OnMultiChoiceClickListener onClick =
				new OnMultiChoiceClickListener() {
			@Override public void onClick(final DialogInterface dialog,
					final int position, final boolean isChecked) {
			}
		};
		build.setView(list);

		build.show();
	}*/

	private byte[] getData() throws IOException{
		Log.e("ENCRYPT",viewflipper.getCurrentView().getId()+" "+R.id.en_view_message);
		byte[] data = null;
		if(viewflipper.getCurrentView().getId() == R.id.en_view_message){
			data = ((TextView)findViewById(R.id.en_inputText)).getText().toString().getBytes();
		}
		if((viewflipper.getCurrentView().getId() == R.id.en_view_browse)){
			if(!TextUtils.isEmpty(selectedFilePath)){
				data = CryptoUtil.getBytesFromFile(new File(selectedFilePath));
			}else{
				Toast.makeText(getApplicationContext(), "Error no file was selected!", Toast.LENGTH_SHORT).show();
			}
		}
		return data;
	}


	private void encrypt() {
		//if(selectedContact == null){
		ForAp app  = ForAp.getInstance();
		try {
			byte[] in = getData();
			byte[] pkey;// = app.getPublicKey().getBytes();
			//byte[] skey = app.getPrivateKey().getBytes();
			//char[] pw = app.getPassword().toCharArray();

			// With passphrase
			/* 
			 * String key = "Iris";
			 * byte[] encrypted = PGPEncryption.encrypt(in, key.toCharArray(),true,true);
				((TextView)findViewById(R.id.encryptOutput)).setText(new String(encrypted));
				byte[] decrypted = PGPEncryption.decrypt(encrypted, key.toCharArray());
				((TextView)findViewById(R.id.decryptOutput)).setText(new String(decrypted));
			 */
			
			//byte[] encrypted = 
			//PGPEncryption.encryptLarge(in, pkey ,true,true);
			setSelectedContact();
			if(!isContactSelected()){
				showErrorBox("No contact selected");
				return;
			}
			pkey = getPublicKeySelectedContact();
			Log.d("d",new String(pkey));

			byte[] encrypted = PGPEncryption.encryptWithPGPKey(in, pkey ,true,true);
			((TextView)findViewById(R.id.encryptOutput)).setText(new String(encrypted));
			/*Log.d("----","-------------------------------------------------------------------------------");
			byte[] decrypted = PGPEncryption.decryptWithPGPKey(encrypted, skey,pw);
			((TextView)findViewById(R.id.decryptOutput)).setText(new String(decrypted));*/
			outputMessage = new String(encrypted);


			showOutputMethod();


		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Encrypt Error: " + e.toString(), Toast.LENGTH_LONG).show();
		}
	}

	

	private void sign() {
		byte[] in = null;
		ForAp app  = ForAp.getInstance();
		try {
			in = getData();			
			byte[] signature = PGPDigitalSignature.signData(in, app.getPrivateKey().getBytes(), app.getPassword().toCharArray());			
			((TextView)findViewById(R.id.encryptOutput)).setText(new String(signature));
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			if(PGPDigitalSignature.verifySignedData(signature, app.getPublicKey().getBytes(),out)){
				Toast.makeText(getApplicationContext(), "Verification Succesfull", Toast.LENGTH_LONG).show();
				//((TextView)findViewById(R.id.decryptOutput)).setText(new String(out.toByteArray()));
			}else{
				Toast.makeText(getApplicationContext(), "Verification FAILED", Toast.LENGTH_LONG).show();
				//((TextView)findViewById(R.id.decryptOutput)).setText("Verification FAILED");
			}

			outputMessage = new String(signature);
			showOutputMethod();
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Sign Error: " + e.toString(), Toast.LENGTH_LONG).show();
		} 
	}

	private void encryptAndSign() {
		byte[] in = null;
		ForAp app  = ForAp.getInstance();
		try {
			setSelectedContact();
			if(!isContactSelected()){
				showErrorBox("No contact selected");
				return;
			}
			byte[] pkey = getPublicKeySelectedContact();
			
			in = getData();			
			byte[] signature = PGPDigitalSignature.signData(in, app.getPrivateKey().getBytes(), app.getPassword().toCharArray());			
			//((TextView)findViewById(R.id.encryptOutput)).setText(new String(signature));

			
			
			byte[] encrypted = PGPEncryption.encryptWithPGPKey(signature, pkey,true,true);
			//((TextView)findViewById(R.id.decryptOutput)).setText(new String(encrypted));

			outputMessage = new String(encrypted);
			showOutputMethod();			
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Encrypt & Sign Error: " + e.toString(), Toast.LENGTH_LONG).show();
		}
	}


	private void showOutputMethod() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Select output method");
		builder.setIcon(R.drawable.icon);
		builder.setItems(outputMethods, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int index) {
				selectedOutput = index;
				processOutput(selectedOutput);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}


	private final CharSequence[] outputMethods = {"Save to File", "Send as SMS", "Send as Email", "Save on DropBox" , "Copy to clipboard","Share"};
	private int selectedOutput;

	private void processOutput(int selectedOutput) {
		switch(selectedOutput){
		case 0://Save to file
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				File sdCard = Environment.getExternalStorageDirectory();
				final File dir = new File (sdCard.getAbsolutePath() + "/ForAp");
				if(!dir.exists())
					dir.mkdirs();
				Intent selectFile = new Intent(EncryptActivity.this, FileExplorerActivity.class);
				selectFile.putExtra(FileExplorerActivity.START_PATH, "/sdcard/forap");
				selectFile.putExtra(FileExplorerActivity.SELECT_ONLY_FOLDER_WRITE, true);
				startActivityForResult(selectFile, SELECT_FOLDER_AND_WRITE);
			}else{
				Toast.makeText(getApplicationContext(), "Error, no (writable) sdcard is mounted!", Toast.LENGTH_SHORT).show();
			}
			break;
		case 1:
			//Send as sms 			
			String phoneNumber = getPhoneNumberSelectedContact();
			if(TextUtils.isEmpty(phoneNumber))
				return;
			String message = outputMessage;
			if(viewflipper.getCurrentView().getId() == R.id.en_view_message){
				Intent sendSms = new Intent(getApplicationContext(), SmsActivity.class);
				sendSms.putExtra("phoneNumber",phoneNumber);
				sendSms.putExtra("message",message);
				startActivity(sendSms);
			}			
			if(viewflipper.getCurrentView().getId() == R.id.en_view_browse){
				String smsbody;
				try {
					smsbody = KeyServerUtil.exchangeEncryptedSMS(message);
					Intent sendSms = new Intent(getApplicationContext(), SmsActivity.class);
					sendSms.putExtra("phoneNumber",phoneNumber);
					sendSms.putExtra("message",smsbody);
					startActivity(sendSms);
				} catch (DropboxException e) {
					Toast.makeText(getApplicationContext(), "DROPBOX ERROR: Sms was not send!", Toast.LENGTH_SHORT).show();
				}
				
			}
			/*Intent intentsms = new Intent( Intent.ACTION_VIEW, Uri.parse( "sms:" + phoneNumber));
			intentsms.putExtra( "sms_body", message );
			startActivity( intentsms );*/
			break;
		case 2:
			//Send as Email
			String email = getEmailSelectedContact();
			if(TextUtils.isEmpty(email))
				return;
			Intent i = new Intent(Intent.ACTION_SEND);
			i.setType("message/rfc822");
			i.putExtra(Intent.EXTRA_EMAIL  , new String[]{email});
			i.putExtra(Intent.EXTRA_SUBJECT, "");
			if(viewflipper.getCurrentView().getId() == R.id.en_view_message){
				i.putExtra(Intent.EXTRA_TEXT , outputMessage);
			}			
			if(viewflipper.getCurrentView().getId() == R.id.en_view_browse){
				try {

					String dir="";
					String[] splitted = selectedFilePath.split("/");
					for(int k=0; k<splitted.length-1;k++){
						dir  = dir.concat(splitted[k]);
						dir = dir.concat("/");
						Log.e("concat",dir +" WTF dir: " + splitted[k] + k);
					}

					Log.e("concat",selectedFilePath +" WTF dir: " + dir+ splitted[splitted.length-1]+".enc");

					File file = new File(dir, splitted[splitted.length-1]+".enc");
					FileOutputStream f;

					f = new FileOutputStream(file,false);

					f.write(outputMessage.getBytes());
					f.close();
					i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), selectedFilePath + ".enc")));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			try {
				startActivity(Intent.createChooser(i, "Send mail..."));
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(EncryptActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
			}
			break;
		case 3:
			//Save to dropbox
			AlertDialog.Builder alert = new AlertDialog.Builder(this);                 
			alert.setTitle("Saving to dropbox");
			if(viewflipper.getCurrentView().getId() == R.id.en_view_message){
				alert.setMessage("Enter the filename");
				final EditText fileName = new EditText(this); 
				alert.setView(fileName);
				alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
					public void onClick(DialogInterface dialog, int whichButton) {
						String fname = fileName.getText().toString() + ".txt.enc";
						if(!TextUtils.isEmpty(fname)){
							DropboxUtil.uploadFile(outputMessage.getBytes(), fname);
							Toast.makeText(getApplicationContext(), "File was saved succesfully", Toast.LENGTH_SHORT).show();
						} else 
							Toast.makeText(getApplicationContext(), "File was not saved! File name is empty", Toast.LENGTH_SHORT).show();
					}  
				});  

				alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(getApplicationContext(), "File was not saved!", Toast.LENGTH_SHORT).show();
						return;   
					}
				});
				alert.show();
			}
			if(viewflipper.getCurrentView().getId() == R.id.en_view_browse){
				String[] splitted = selectedFilePath.split("/");
				final String fname = splitted[splitted.length-1] + ".enc";
				alert.setMessage("Filename: " + fname );
				alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
					public void onClick(DialogInterface dialog, int whichButton) {

						DropboxUtil.uploadFile(outputMessage.getBytes(), fname);
						Toast.makeText(getApplicationContext(), "File was saved succesfully", Toast.LENGTH_SHORT).show();

					}  
				});  

				alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(getApplicationContext(), "File was not saved!", Toast.LENGTH_SHORT).show();
						return;   
					}
				});
				alert.show();
			}
			break;
		case 4:
			//Copy to clipboard
			ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			clipboard.setText(outputMessage);
			break;
		case 5:
			//Share
			Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, outputMessage);
			try {
				startActivity(Intent.createChooser(sharingIntent, "Share via"));
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(EncryptActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
			}			
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_CONTACT_REQUEST) {
			if (resultCode == RESULT_OK) {
				/*datasource.open(); // on resume isnt called yet
				long id = data.getExtras().getLong("contactId");
				Log.i("resultID","  " +id);
				selectedContact = datasource.getContact(id);
				((AutoCompleteTextView) findViewById(R.id.en_autoCompleteContact)).setText(selectedContact.getName());*/
			}
		}
		if (requestCode == SELECT_FILE) {
			if (resultCode == Activity.RESULT_OK) {				 
				selectedFilePath = data.getStringExtra(FileExplorerActivity.RESULT_PATH);
				((TextView) findViewById(R.id.en_textview_selectedFile)).setText("Selected file: "+ selectedFilePath);
			} else if (resultCode == Activity.RESULT_CANCELED) {
				((TextView) findViewById(R.id.en_textview_selectedFile)).setText("Selected file: "+ "Error selecting a file");
			}
		}
		if (requestCode == SELECT_FOLDER_AND_WRITE) {
			if (resultCode == Activity.RESULT_OK) {		
				final String folderPath = data.getStringExtra(FileExplorerActivity.RESULT_PATH);
				AlertDialog.Builder alert = new AlertDialog.Builder(this);   
				alert.setTitle("Saving to sd card");
				if(viewflipper.getCurrentView().getId() == R.id.en_view_message){
					alert.setMessage("Enter Filename");
					// Set an EditText view to get user input   
					final EditText input = new EditText(this); 
					alert.setView(input);
					alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int whichButton) {
							FileOutputStream fos;
							try {	
								File file = new File(folderPath, input.getText().toString() + ".txt.enc");
								FileOutputStream f = new FileOutputStream(file,false);
								f.write(outputMessage.getBytes());
								f.close();
								Toast.makeText(getApplicationContext(), "File was saved succesfully", Toast.LENGTH_SHORT).show();
							} catch (FileNotFoundException e) {
								Toast.makeText(getApplicationContext(), "Error while saving the file!", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}	catch (IOException e) {
								Toast.makeText(getApplicationContext(), "Error while saving the file!", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}					                
						}  
					});  
				}
				if(viewflipper.getCurrentView().getId() == R.id.en_view_browse){
					final String[] splitted = selectedFilePath.split("/");
					final String fName =  splitted[splitted.length-1]+".enc";
					alert.setMessage("Filename: "+ fName); 
					alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
						public void onClick(DialogInterface dialog, int whichButton) {
							FileOutputStream fos;
							try {
								File file = new File(folderPath, fName);
								FileOutputStream f = new FileOutputStream(file,false);
								f.write(outputMessage.getBytes());
								f.close();
								Toast.makeText(getApplicationContext(), "File was saved succesfully", Toast.LENGTH_SHORT).show();
							} catch (FileNotFoundException e) {
								Toast.makeText(getApplicationContext(), "Error while saving the file!", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}	catch (IOException e) {
								Toast.makeText(getApplicationContext(), "Error while saving the file!", Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}					                
						}  
					});  
				}
				alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						Toast.makeText(getApplicationContext(), "File was not saved!", Toast.LENGTH_SHORT).show();
						return;   
					}
				});
				alert.show();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				((TextView) findViewById(R.id.en_textview_selectedFile)).setText("Error selecting a folder");
			}
		}

	}

	private void updateSelectedLabel() {
		switch (viewflipper.getCurrentView().getId()) {
		case R.id.en_view_message: {
			selected.setText("Message");
			break;
		}
		case R.id.en_view_browse: {
			selected.setText("File");
			break;
		}
		default: {
			break;
		}
		}
	}
	
	ForapAdapter contactsAdapter;
	boolean[] checkedList;
	
	private void popupContactSelect(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		final String[] contactList = contactsAdapter.getDisplayNames();
		

		builder.setTitle("Select contact")
		.setMultiChoiceItems(contactList, checkedList,	new DialogInterface.OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {}
		})		
		.setPositiveButton("Select", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				ListView list = ((AlertDialog)dialog).getListView();
				StringBuilder sb = new StringBuilder();
				ArrayList<RowData> selectedRows = new ArrayList<RowData>();
				for (int i=0; i<list.getCount(); i++) {
					boolean checked = list.isItemChecked(i);

					if (checked) {
						checkedList[i] = true;
						selectedRows.add(contactsAdapter.getRow(i));
						//if (sb.length()>0) sb.append(", ");
						//sb.append(list.getItemAtPosition(i));
					}
				}
				procesContactSelection(selectedRows);
				//Toast.makeText(getApplicationContext(), "Selected contact: " + sb.toString(), Toast.LENGTH_SHORT).show();
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		})
		.create();
		builder.show();
	}
	
	private void procesContactSelection(ArrayList<RowData> selectedRows) {
		String sep = contactInput.getSeperator();
		String text = "";
		for(RowData rd:selectedRows){
			text = text + rd.getDisplayName() + sep;
		}
		contactInput.setText(text);
	}
	
	private RawContact selectedContact = null;
	private boolean usingOwnPublicKey = false;
	
	private void setSelectedContact(){
		for(int i =0; i<checkedList.length;i++){
			if(checkedList[i]){
				if(contactsAdapter.isPersonalRow(i)){
					usingOwnPublicKey = true;
				}else{
					selectedContact = ContactManager.getRawContactInfo(this, contactsAdapter.getForapGlobalId(i));
				}				
			}
		}
	}
	
	private boolean isContactSelected(){
		return usingOwnPublicKey || (selectedContact != null);
	}
	
	private byte[] getPublicKeySelectedContact() {
		if(usingOwnPublicKey)
			return ForAp.getInstance().getPublicKey().getBytes();
		//check integrity
		String status = "";
		ContactsIntegrityDb db = new ContactsIntegrityDb(this);
		db.open();
		ContactIntegrityElement cie = db.getContactIntegrity(selectedContact.getGlobalContactId());
		db.close();
		if(!cie.verifyIntegrity(selectedContact)){
			showErrorBox("Public key integrity test failed! This false public key is now deleted.");
			ContactManager.deleteContact(getApplicationContext(), selectedContact.getGlobalContactId());
		}
		status = "Public key integrity verified.";
		Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
		
		return selectedContact.getPublicKeyBlock().getBytes();
	}
	
	private String getPhoneNumberSelectedContact() {
		if(usingOwnPublicKey)
			return "0479409147";//for testing purpose
		String pn = selectedContact.getCellPhone();
		if(TextUtils.isEmpty(pn)){
			showErrorBox("The selected contact: "+ selectedContact.getBestName() +" has no phone number.");
			return "";
		}
		return pn;
	}
	
	private String getEmailSelectedContact() {
		if(usingOwnPublicKey)
			return(ForAp.getInstance().getUser());
		String pn = selectedContact.getEmail();
		if(TextUtils.isEmpty(pn)){
			showErrorBox("The selected contact: "+ selectedContact.getBestName() +" has no email.");
			return "";
		}
		return pn;
	}
	
	private void showErrorBox(String title){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(false);
		builder.setTitle(title);
		builder.setIcon(R.drawable.ic_red_cross);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

}